package com.jhgsys.internal.common.configure;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig {

    @Value("${jebs.cors.domain}")
    private String corsDomain;

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", buildConfig());
        source.registerCorsConfiguration("/wx/callback", buildConfigAllGet());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
        filterRegistrationBean.setOrder(100);
        return filterRegistrationBean;
    }

    /*支持JS跨域访问*/
    private CorsConfiguration buildConfigAllGet() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 可以自行筛选
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("GET");//"*" "GET", "POST", "DELETE", "PUT", "OPTIONS"
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    /*支持JS跨域访问*/
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 可以自行筛选
        List<String> domains = Arrays.asList(corsDomain.split(","));
        corsConfiguration.setAllowedOrigins(domains);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("GET");//"*" "GET", "POST", "DELETE", "PUT", "OPTIONS"
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
}
